﻿#include "PortThread.h"
#include "realtimedb.h"
#include <QDebug>


PortThread::PortThread(QString name)
{
    m_name = name;
    mbIsRunning = false;
    state = __Thread_Stop;
}

PortThread::~PortThread()
{

}

void PortThread::AddDevice(Device *pDevice)
{
    qDebug() << "PortThread::AddDevice:Name " << pDevice->getDeviceName() << "Port " << pDevice->getPortName();
    m_DeviceList.append(pDevice);
}

/*
* 是否运行
*/
bool PortThread::IsRunning()
{
    return mbIsRunning;
}


/*
* 启动
*/
void PortThread::Start()
{
    if(mbIsRunning) {
        return;
    }
    mbIsRunning = true;
    this->start();
}


/*
* 停止
*/
void PortThread::Stop()
{
    mbIsRunning = false;
    foreach (Device *pDevice, m_DeviceList) {
        if(pDevice != NULL) {
            if(pDevice->isRunning()) {
                pDevice->stop();
                pDevice->close();
            }
        }
    }
    while(state != __Thread_Stop)
    {
        this->msleep(5);
    }
    this->wait();
}


void PortThread::run()
{
    qDebug()<< "PortThread::run:" << m_name << " Dev Count:" << m_DeviceList.size();

    foreach (Device *pDevice, m_DeviceList) {
        qDebug() << "PortThread::run" << pDevice->getDeviceName()  << " Port:" << pDevice->getPortName();
        if(pDevice != NULL) {
            qDebug() << "PortThread::run" << pDevice->getDeviceName()  << " Port:" << pDevice->getPortName() << " Running:" << pDevice->isRunning();

            if(!pDevice->isRunning()) {
                qDebug() << "PortThread::run" << pDevice->getDeviceName()  << " Port:" << pDevice->getPortName() << " Open Device";
                pDevice->open();
                qDebug() << "PortThread::run" << pDevice->getDeviceName()  << " Port:" << pDevice->getPortName() << " Init Device";
                pDevice->initialize();
                qDebug() << "PortThread::run" << pDevice->getDeviceName()  << " Port:" << pDevice->getPortName() << " Start Device";
                pDevice->start();
            }
        }
    }
    state = __Thread_Runing;

    while(mbIsRunning) {
        foreach (Device *pDevice, m_DeviceList) {
            if(!mbIsRunning)
                break;
            if(pDevice != Q_NULLPTR) {
                pDevice->doLoop();
            }
            //qDebug() << "PortThread::run:DoLoop->" << pDevice->getDeviceName();
        }
        this->msleep(5);
        //是否需要在此将数据更新到widget中？还是在widget中直接访问RtDb?
    }
    qDebug()<< "PortThread run end.";
    state = __Thread_Stop;
}

